package cn.edu.sdjzu.xg.eagle.util;

import cn.edu.sdjzu.xg.eagle.entity.Pagination;
import cn.edu.sdjzu.xg.eagle.entity.Condition;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 *  ControllerHelper 工具类
 *  功能：解析前端请求的 JSON 数据，提取分页信息与查询条件
 */

public class ControllerHelper {

    /**
     *  从请求的 JSON 对象中提取查询条件列表（conditionList）
     */

    public static List<Condition> getConditions(JSONObject requestJson) {
        List<Condition> conditions = new ArrayList<>();
        JSONArray conditionArray = requestJson.getJSONArray("conditionList");
        for (int i = 0; i < conditionArray.size(); i++) {
            JSONObject conditionObj = conditionArray.getJSONObject(i);
            String key = conditionObj.getString("key");
            String operate = conditionObj.getString("operate");
            String value = conditionObj.getString("value");
            conditions.add(new Condition(key, value, operate));
        }
        return conditions;
    }

    /**
     *  从请求的 JSON 对象中提取分页信息(Pagination)
     */

    public static Pagination getPagination(JSONObject req_jsonObj) {
        JSONObject pagination_jsonObj = req_jsonObj.getJSONObject("pagination");
        Pagination pagination = null;
        if (pagination_jsonObj != null) {
            pagination = pagination_jsonObj.toJavaObject(Pagination.class);
        }
        return pagination;
    }
}
